(() => {

    let ele = {};

    ele.explain = $('#explain');
    ele.modal_explain = $('#modal-explain');
    ele.close = $('#close');
    ele.close2 = $('#close2');

    ele.list = $('#list');
    ele.all_luxury = $('#all_luxury')

    var countdownInterval  //定时器
    var js

    // 玩法说明
    ele.close.onclick = () => {
        ele.modal_explain.style.display = 'none'
    }
    ele.close2.onclick = () => {
        ele.modal_explain.style.display = 'none'
    }
    ele.explain.onclick = () => {
        ele.modal_explain.style.display = 'block'
    }

    // socket
    const wsuri = 'ws://ws.hfksh.cn:2346'
    let socket = null
    var timer
    let list = ''

    
    // 链接websocket
//     document.addEventListener("visibilitychange", function() {
// 		alert(document.visibilityState);
// 		//页面显示时document.visibilityState值为visible，隐藏显示时document.visibilityState值为hidden， 
// 		//或者
// 		//这个是判断document.hidden，页面的隐藏状态
//         if(document.visibilityState == 'hidden') {
//             socket.close()
//         }else {
//             getzhengba()
//         }
// 	});



    window.addEventListener('pageshow', function(event) {
        //event.persisted属性为true时，表示当前文档是从往返缓存中获取
        if(event.persisted) location.reload();  
    });
    
     window.addEventListener('pagehide', function(event) {
       socket.close()
    });
    
    

    

    // 获取个人信息接口
    getUserInfo((res) => {
        // console.log(res);
        ele.all_luxury.innerHTML = res.all_luxury
    })

    // 获取列表
    function getlist() {
        let data = {
            type: 'index',
            data: {}
        }
        socket.send(JSON.stringify(data))
    }

    getzhengba()
    // 获取争霸赛列表
    function getzhengba(){

        let token = getCookie("token");
        ajax({
			url: API_PATH.ZHENGBA,
			method: 'GET',
			header: {
				'Authorization': token
			},
			success: res => {
				if (res.code == 200) {
                    drawinfo(res.data.list)
                    list = res.data.list
                    startWebSocket()
				}
			}
		});
    }

    // 链接websocket
    function startWebSocket() {
        socket = new WebSocket(wsuri)
        //监听消息接收事件
        socket.addEventListener('message', onMessage)

        //监听WebSocket连接事件
        socket.addEventListener('open', onOpen)

        //监听WebSocket异常事件
        socket.addEventListener('error', onError)

        //监听WebSockt关闭事件
        socket.addEventListener('close', onClose)
    }

    //监听WebSocket连接事件
    function onOpen() {
        let id = getCookie('userid')
        let data = {
            type: 'login',
            data: {
                u_id: id
            }
        }
        socket.send(JSON.stringify(data))
        heart()
    }

    // 设置心跳
    function heart() {
        clearInterval(timer);
        let data = {
            type: "pong",
            data:{}
        }
        timer = setInterval(() => {
            // 传递参数给服务器
            socket.send(JSON.stringify(data))
        }, 30000)
    }

    //监听WebSocket异常事件
    function onError(e) {
        console.error(e)
        startWebSocket()
    }
    //监听消息接收事件
    function onMessage(e) {
        if (!e) return
        // console.log(e.data)
        let data = JSON.parse(e.data)
        // console.log(data)
      
        switch (data.type) {
            case 'login': 
                getlist(); // 绑定用户 发送u_id
                break;
            case 'index':
                // drawinfo(data.data.list) // 渲染列表
                break;
            case 'error':
                openTips(data.msg)
                break;
            case 'enroll':
                openTips(data.msg)
                enroll(data.data)
                // drawinfo(data.data.list)
                break;
            case 'change':
                numchange(data.data)
                break;
            case 'game_start':
                location.href = 'competition.html?id=' + data.data.room_id
                break;
            case 'back':
                openTips(data.msg)
                drawinfo(list)
                break;
        }
    }

    //监听WebSockt关闭事件
    function onClose(e) {
        console.log('WebSocket disconnected.', e)
    }

    // 报名成功改变状态
    function enroll(data){
        // console.log(data);
        let type = data.c_id-1
        let item = $('.item' + data.c_id)[0];
        let html = '<div class="after">' +
                    '<img  src="http://img.qxgs.cc/tiantianlaishouzu/img/hegemony/pic.png" alt="">' +
                    '</div>' +
                    '<div class="title">' +
                    '<img class="posaimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/hegemony/hengfu.png" alt="">' +
                    '<span>争夺' + list[type].income + '金币</span>' +
                    '</div>' +
                    '<p class="p_num" id="changenum">人数达到 <span >' + data.player_num + '/' + list[type].join_num+ '</span> 时，比赛开始</p>' +
                    '<p class="time" id="daojishi" data="' + data.created_at + '">3:00</p>' +
                    '<p class="explain">倒计时结束后人数未满，退还报名费用</p>' ;

        item.innerHTML = html
        daojishi()
        clearInterval(js)
    }
    
    // 修改参与人数
    function numchange(data) {
        let changenum = $('#changenum');
        changenum.innerHTML = '人数达到<span >' + data.player_num +'/' + data.join_num + '</span> 时，比赛开始'
    }

    // 渲染列表
    function drawinfo(data) {
        let html = ''
        for (let i = 0; i < data.length; i++) {
            let d = data[i];
                html += '<div class="item item'+d.c_id+'">' +
                    '<div>' +
                    '<img src="http://img.qxgs.cc/tiantianlaishouzu/img/hegemony/pic.png" alt="">' +
                    '</div>' +
                    '<div class="title">' +
                    '<img class="posaimg" src="http://img.qxgs.cc/tiantianlaishouzu/img/hegemony/hengfu.png" alt="">' +
                    '<span>争夺' + d.income + '金币</span>' +
                    '</div>' +
                    '<div class="center">豪华值：' + d.start_luxury + '-' + d.end_luxury + '</div>' +
                    '<button class="btn" onclick="baoming(' + d.c_id + ')">' + d.registration_fee + '金币报名</button>' +
                    '</div>';
        }
        ele.list.innerHTML = html
    }

    // 报名事件
    window.baoming = function baoming(id) {
        // console.log(id);
        let data = {
            type: 'enroll',
            data: {
                c_id:id
            }
        }
        socket.send(JSON.stringify(data))
    }

    // 进行倒计时
    function daojishi(room_id) {
        let daojishi = $('#daojishi');
        let time = daojishi.getAttribute('data')
        // 每秒钟更新一次倒计时
        clearInterval(countdownInterval)
        countdownInterval = setInterval(() => {
            countdown(time, room_id)
        }, 1000)
    }

    // 倒计时逻辑
    function countdown(time, room_id) {
        let daojishi = $('#daojishi');
        // 当前时间戳（单位：毫秒）
        let currentTimestamp = new Date().getTime();
        // 计算剩余时间（单位：毫秒）
        let remainingTime = (time * 1000 + 180000) - currentTimestamp;
        var remainingMinutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
        var remainingSeconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
        daojishi.innerHTML = localStorage.getItem('remainingMinutes') + ':' + localStorage.getItem('remainingSeconds')
        // 如果剩余时间小于等于0，则停止倒计时
        if (remainingSeconds < 10) {
            remainingSeconds = '0' + remainingSeconds
        }
        if (remainingTime <= 0) {
            clearInterval(countdownInterval);
            daojishi.innerHTML = '00:00';
            return;
        }
        // 计算剩余天数、小时数、分钟数、秒数
        // console.log(remainingMinutes, remainingSeconds);
        // 更新倒计时元素内容
        daojishi.innerHTML = remainingMinutes + ':' + remainingSeconds

    }








})();



